package jsp;

import util.CookieUtil;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/showMain")
public class ShowMainServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 取出Cookie中存储的username与password
        String username = CookieUtil.findByName("username", req);
        String password = CookieUtil.findByName("password", req);

        // 判断Cookie中是否存在用户名与密码
        if (StringUtil.isNull(username) || StringUtil.isNull(password)) {
            // 此时不需要进入数据库查询,直接跳转到登录页面
            req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
        } else {
            // 如果存在,则进入数据库查询,判断当前Cookie中保存的用户名与密码是否正确
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8", "root", "root");
                String sql = new StringBuffer()
                        .append(" select id,username,password,phone,address ")
                        .append(" from t_user ")
                        .append(" where username = ? ")
                        .append(" and password = ? ")
                        .toString();
                ps = conn.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, password);
                rs = ps.executeQuery();
                if (rs.next()) {
                    // 如果查询到结果了,则说明Cookie中的用户名与密码正确
                    // 此时不需要经过登录页面,直接跳转到主页
                    req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
                    return;
                }
                // 如果没有进入分支,说明没有查询到结果,即:用户名或密码错误
                // 此时可以Cookie保存的错误的用户名与密码移除
                CookieUtil.removeCookie("username", resp);
                CookieUtil.removeCookie("password", resp);
                // 跳转到登录页面进行登录
                req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }
}
